package com.springboot.middleware.middleware_grab_red_envelopes.server.controller;

import com.springboot.middleware.middleware_grab_red_envelopes.api.enums.StatusCode;
import com.springboot.middleware.middleware_grab_red_envelopes.api.response.BaseResponse;
import com.springboot.middleware.middleware_grab_red_envelopes.server.dto.RedPacketDto;
import com.springboot.middleware.middleware_grab_red_envelopes.server.service.RedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * 红包处理逻辑Controller
 */
@RestController
public class RedPacketController {
    private static final Logger log = LoggerFactory.getLogger(RedPacketController.class);

    private static final String prefix = "red/packet";

    @Autowired
    private RedPacketService redPacketService;

    /**
     * 发红包请求-请求方法为Post,请求参数采用Json格式进行交互
     */
    @RequestMapping(value = prefix + "/hand/out", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResponse handOut(@Validated @RequestBody RedPacketDto dto, BindingResult result) {
        if (result.hasErrors()) {
            return new BaseResponse(StatusCode.InvalidParams);
        }
        BaseResponse baseResponse = new BaseResponse(StatusCode.Success);
        try {
            String redId = redPacketService.handOut(dto);
            baseResponse.setData(redId);
        } catch (Exception e) {
            log.error("发红包发生异常: dto={}", dto, e.fillInStackTrace());
            baseResponse = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return baseResponse;
    }

    /**
     * 抢红包请求: 接收当前用户账户id和红包全局唯一标识串为参数
     */
    @RequestMapping(value = prefix + "/rob", method = RequestMethod.POST)
    public BaseResponse rob(@RequestParam Integer userId, @RequestParam String redId) {
        BaseResponse baseResponse = new BaseResponse(StatusCode.Success);
        try {
            //调用红包业务逻辑处理接口中的抢红包方法,最终返回抢到的红包金额
            BigDecimal result = redPacketService.rob(userId, redId);
            if (result != null) {
                baseResponse.setData(result);
            } else {
                baseResponse = new BaseResponse(StatusCode.Fail.getCode(), "红包已经被抢完!");
            }
        } catch (Exception e) {
            log.error("抢红包发生异常, userId = {}, redId = {}", userId, redId);
            baseResponse = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return baseResponse;
    }
}
